package com.huirui.server.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class MinioConfig {

    @Value("${huirui.minio.endpoint}")
    private String endpoint;

    @Value("${huirui.minio.access-key}")
    private String accessKey;

    @Value("${huirui.minio.secret-key}")
    private String secretKey;

    @Value("${huirui.minio.bucket-name}")
    private String bucketName;

    /**
     * 初始化 MinIO 客户端
     */
    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        log.info("正在初始化存储桶！");
        try {
            // 检查存储桶是否存在
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build());

            if (!exists) {
                // 不存在则创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
                log.info("存储桶创建成功：{}", bucketName);
            } else {
                log.info("存储桶已存在：{}", bucketName);
            }
        } catch (Exception e) {
            log.error("MinIO客户端初始化失败！请检查服务是否可用或配置是否正确", e);
            throw new RuntimeException("初始化MinIO存储桶失败", e);
        }
        return minioClient;
    }



}
